package com.zw.healthy.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zw.api.UserFeignClient;
import com.zw.commons.utlis.JwtHelper;
import com.zw.commons.utlis.SaveImage;
import com.zw.commons.utlis.baiduai.EasyDlImageClassify;
import com.zw.commons.utlis.baiduai.FileReferUtil;
import com.zw.object.healthy.HealthClock;
import com.zw.object.healthy.HealthReport;
import com.zw.healthy.mapper.HealthReportMapper;
import com.zw.healthy.service.HealthReportService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zw.object.result.Result;
import com.zw.object.system.SysUser;
import com.zw.object.vo.HealthyReportVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * <p>
 * 二码一报告表 服务实现类
 * </p>
 *
 * @author zw
 * @since 2023-03-16
 */
@Slf4j
@Service
public class HealthReportServiceImpl extends ServiceImpl<HealthReportMapper, HealthReport> implements HealthReportService {

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Result list(HealthyReportVo vo, HttpServletRequest request) {
        String username = JwtHelper.getUsername(request.getHeader("token"));
        SysUser user = userFeignClient.getUserByUsername(username);
        LambdaQueryWrapper<HealthReport> wrapper = new LambdaQueryWrapper<>();
        Page<HealthReport> page = new Page<>(vo.getPageNum(), vo.getPageSize());
        if(user!=null && "学生".equals(user.getDescription())){
            wrapper.eq(HealthReport::getUsername,username);
            wrapper.orderByAsc(HealthReport::getCreateTime);
            Page<HealthReport> healthReportPage = baseMapper.selectPage(page, wrapper);
            return Result.ok(healthReportPage);
        }
        wrapper.like(StrUtil.isNotBlank(username), HealthReport::getUsername, username);
        wrapper.eq(vo.getDeptId() != null, HealthReport::getDeptId, vo.getDeptId());
        wrapper.eq(vo.getType() != null, HealthReport::getType, vo.getType());
        if (StrUtil.isNotBlank(vo.getStart()) && StrUtil.isNotBlank(vo.getEnd())){
            DateTime a = DateUtil.parse(vo.getStart() + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
            DateTime b = DateUtil.parse(vo.getEnd() + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
            wrapper.between(HealthReport::getCreateTime, a, b);
        }
        wrapper.orderByDesc(HealthReport::getCreateTime);
        Page<HealthReport> reportPage = baseMapper.selectPage(page, wrapper);
        return Result.ok(reportPage);
    }

    @Override
    public Result checkReportToday(HttpServletRequest request) {
        LambdaQueryWrapper<HealthReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HealthReport::getUsername, JwtHelper.getUsername(request.getHeader("token")))
                .apply("to_days(create_time) = to_days(now())");
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0 ? Result.ok("今日已上报，请不要重复上报"):Result.ok("allow");
    }

    @Override
    public Result save(MultipartFile file1, MultipartFile file2, MultipartFile file3, Integer type, HttpServletRequest request) throws Exception {
        HealthReport report = new HealthReport();
        SaveImage saveImage = new SaveImage();
        // todo:百度飞浆得健康吗识别
        File file= FileReferUtil.multipartFileToFile(file1);
        String name = EasyDlImageClassify.easyDlImageClassify(file);
        report.setHealthCodeColourRes(name);
        log.info("健康码颜色识别结果"+name);
        report.setType(type);
        if (!file1.isEmpty() && !file2.isEmpty() && !file3.isEmpty()){
            String saveImage1 = saveImage.saveImage(file1);
            String saveImage2 = saveImage.saveImage(file2);
            String saveImage3 = saveImage.saveImage(file3);
            report.setImg1(saveImage1);
            report.setImg2(saveImage2);
            report.setImg3(saveImage3);
        }
        SysUser user = userFeignClient.getUserByUsername(JwtHelper.getUsername(request.getHeader("token")));
        report.setUsername(user.getUsername());
        report.setPhoneNumber(user.getPhone());
//        TODO://部门未进行规划，目前制作填充
        report.setDeptId(1L);
        int insert = baseMapper.insert(report);
        return insert>0?Result.ok():Result.fail();
    }
}
